package com.mvd.app.ac2021;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.activity.PhotoPreviewActivity;
import com.mvd.app.ac2021.adapter.Wai_6M_PhotoAdapter;
import com.mvd.app.adapter.MyProvincesListAdapter2;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.Constants;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.SystemUtil;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.model.PictureModel;
import com.mvd.app.model.RecheckCarsModel;
import com.mvd.app.model.TypeModel;
import com.mvd.app.model.UploadPhotoModel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.mvd.app.application.BaseApplication.WAIJIAN_PHOTO_PREVIEW_LISTS;

/**
 * @author Administrator
 * @version V1.0
 * @Title: Wai_6M_PhotoActivity
 * @Package com.mvd.app.ac2021.activitys
 * @Description: 6米以上高度拍摄--照片
 * @date 2020-12-28 13:44
 **/

public class Wai_6M_PhotoActivity extends TakePhotoActivity implements ApiConfig {


    @BindView(R.id.ac_6m_photo_ib_back)
    ImageButton ac6mPhotoIbBack;
    @BindView(R.id.ac_6m_photo_title_txt)
    TextView ac6mPhotoTitleTxt;
    @BindView(R.id.ac_6m_photo_listview)
    ListView ac6mPhotoListview;
    @BindView(R.id.ac_6m_photo_btn_other_imags)
    Button ac6mPhotoBtnOtherImags;
    @BindView(R.id.ac_6m_photo_btn_buhege2)
    Button ac6mPhotoBtnBuhege2;
    @BindView(R.id.ac_6m_photo_btn_wancheng2)
    Button ac6mPhotoBtnWancheng2;
    @BindView(R.id.ac_6m_photo_ll_bottom_layout)
    LinearLayout ac6mPhotoLlBottomLayout;
    @BindView(R.id.ac_6m_photo_scrollview)
    ScrollView ac6mPhotoScrollview;
    @BindView(R.id.ac_wai_6m_line)
    TextView acWai6mLine;
    private Wai_6M_PhotoActivity instances = null;
    private String carNo = null, Line = "1";//车牌号码
    private String PHOTO_TYPE = "";//外检拍照的TYPE上传类型
    private String Item_Code = "F1";

    TakePhoto takePhoto;
    Uri imageUri;
    private CarsInforModel carsInforModel;
    private String Login_name, login_IDNumber;
    private RecheckCarsModel recheckCarsModel;
    int flag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.activity_6m_photo);
        ButterKnife.bind(this);
        instances = this;
        init();
//        carsInforModel = (CarsInforModel) getIntent().getSerializableExtra("model_CarsInforModel");
//        Login_name = getIntent().getExtras().getString("login_w_name", "");
//        login_IDNumber = getIntent().getExtras().getString("login_IDNumber", "");
//        Line = getIntent().getExtras().getString("Car_Line", "1");
//
//        UtilsLog.e("recheckCarsModel==" + carsInforModel.toString());
//        String logStr = "\n" + "onCreate--6米以上高度拍摄--照片--车辆信息--carsInforModel-" + "\n" +
//                "carsInforModel:" + "\n" + carsInforModel.toString() + "\n" +
//                "Login_name:" + Login_name + "\n" + "login_IDNumber:" + login_IDNumber + "\n";
//        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//
//        //车牌号码
//        if ( !TextUtils.isEmpty(carsInforModel.getPlateNO())) {
//            carNo = carsInforModel.getPlateNO();
//        }
        pop_xuhao();
        if (getIntent() != null) {
            Login_name = getIntent().getExtras().getString("login_w_name", "");
            login_IDNumber = getIntent().getExtras().getString("login_IDNumber", "");
            flag = getIntent().getExtras().getInt("flag", 0);
//            if (flag == 0) {
            carsInforModel = (CarsInforModel) getIntent().getSerializableExtra("model_CarsInforModel");
            UtilsLog.e("recheckCarsModel==" + carsInforModel.toString());
            Line = getIntent().getExtras().getString("Car_Line", "1");
            String logStr = "\n" + "onCreate--6米以上高度拍摄--照片--车辆信息--carsInforModel-" + "\n" +
                    "carsInforModel:" + "\n" + carsInforModel.toString() + "\n" +
                    "Login_name:" + Login_name + "\n" + "login_IDNumber:" + login_IDNumber + "\n" +
                    "line:" + Line + "\n";
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
            //车牌号码
            if (!TextUtils.isEmpty(carsInforModel.getPlateNO())) {
                carNo = carsInforModel.getPlateNO();
            }
//            } else if (flag == 1) {
//                recheckCarsModel = (RecheckCarsModel) getIntent().getSerializableExtra("model_CarsInforModel");
//                Line = String.valueOf(recheckCarsModel.getLine());
//                UtilsLog.e("recheckCarsModel==" + recheckCarsModel.toString());
//                String logStr = "\n" + "onCreate--6米以上高度拍摄--照片--车辆信息--recheckCarsModel-" + "\n" +
//                        "recheckCarsModel:" + "\n" + recheckCarsModel.toString() + "\n" +
//                        "Login_name:" + Login_name + "\n" + "login_IDNumber:" + login_IDNumber + "\n"
//                        + "line:" + Line + "\n";
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                //车牌号码
//                if (!TextUtils.isEmpty(recheckCarsModel.getPlateRegion()) &&
//                        !TextUtils.isEmpty(recheckCarsModel.getPlateNO())) {
//                    carNo = recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO();
//                }
//            }
            acWai6mLine.setText(Line);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (CommonUtils.isOnline(instances)) {
        } else {
            Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
                    .LENGTH_LONG).show();
        }
    }

    //popuwindow
    private View popu_xuhao_view;
    private LinearLayout parent22;
    private PopupWindow pop_xuhao = null;
    private ListView listview_xuhao;
    private MyProvincesListAdapter2 myProAdapter;
    private List<String> xuhaoList = new ArrayList<String>();

    private void pop_xuhao() {
        for (int i = 0; i < Constants.WAIJIAN_CHEDAO_CHEJIAN_XIANHAO.length; i++) {
            xuhaoList.add(i, Constants.WAIJIAN_CHEDAO_CHEJIAN_XIANHAO[i]);
        }
        pop_xuhao = new PopupWindow(this);
        popu_xuhao_view = getLayoutInflater().inflate(R.layout.item_setting_province_letter,
                null);
        pop_xuhao.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        pop_xuhao.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        pop_xuhao.setBackgroundDrawable(new BitmapDrawable());
        pop_xuhao.setFocusable(true);
        pop_xuhao.setOutsideTouchable(true);
        pop_xuhao.setContentView(popu_xuhao_view);
        parent22 = (LinearLayout) popu_xuhao_view.findViewById(R.id.setting_provinces_parent);
        listview_xuhao = (ListView) popu_xuhao_view.findViewById(R.id.setting_provinces_listview2);
        myProAdapter = new MyProvincesListAdapter2(this, xuhaoList);
        listview_xuhao.setAdapter(myProAdapter);
        listview_xuhao.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                acWai6mLine.setText(xuhaoList.get(position));
                Line = xuhaoList.get(position);
                pop_xuhao.dismiss();
            }
        });
        parent22.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop_xuhao.dismiss();
            }
        });
    }

    Wai_6M_PhotoAdapter contentAdapter2;
    List<TypeModel> typeModelListAdapter = null;

    private void init() {
        typeModelListAdapter = new ArrayList<>();
        TypeModel typeModel = null;
        for (int i = 0; i < Constants.WAI_6M_PHOTO_TYPE_LISTS.length; i++) {
            typeModel = new TypeModel();
            typeModel.setName(Constants.WAI_6M_PHOTO_TYPE_LISTS[i][0] + "-" + Constants.WAI_6M_PHOTO_TYPE_LISTS[i][1]);
            typeModel.setCode(Constants.WAI_6M_PHOTO_TYPE_LISTS[i][1]);
            typeModelListAdapter.add(typeModel);
        }
        contentAdapter2 = new Wai_6M_PhotoAdapter(instances, typeModelListAdapter,
                mListener);
        //实例化ContentAdapter2类，并传入实现类
        ac6mPhotoListview.setAdapter(contentAdapter2);
        setListViewHeightBasedONChildren(ac6mPhotoListview);
    }

    public static void setListViewHeightBasedONChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Log.e("tag", "6米以上高度拍摄--照片失败==" + msg);
        String logStr = "\n" + "6米以上高度拍摄--照片----拍照失败==" + "\n" + msg;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        ArrayList<TImage> images = result.getImages();
        if (images != null && images.size() > 0) {
            String photo_file_path = images.get(0).getCompressPath();
            String photo_file_path2 = images.get(0).getOriginalPath();
            Log.e("tag", "6米以上高度拍摄--照片拍照失败--path==" + photo_file_path);
            Log.e("tag", "6米以上高度拍摄--照片拍照失败--path=22=" + photo_file_path2);
        }
    }

    int FLAG = 1;//0:拍照   1：相册

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
    }

    /**
     * 实现类，响应按钮点击事件
     */
    int TypeModel_Position = 0;

    Wai_6M_PhotoAdapter.MyClickListener mListener = new Wai_6M_PhotoAdapter.MyClickListener() {
        @Override
        public void myOnClick(int position, View v, int flag) {
            PHOTO_TYPE = typeModelListAdapter.get(position).getCode();
            TypeModel_Position = position;
            FLAG = flag;
            if (position == 0) {
                getDataTakePhoto("A110");
            } else if (position == 1) {
                getDataTakePhoto("A111");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        instances = null;
    }

    @OnClick({R.id.ac_6m_photo_ib_back, R.id.ac_6m_photo_btn_other_imags,
            R.id.ac_6m_photo_btn_buhege2, R.id.ac_6m_photo_btn_wancheng2,
            R.id.ac_wai_6m_line})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ac_wai_6m_line:
                pop_xuhao.showAsDropDown(acWai6mLine);
                break;
            case R.id.ac_6m_photo_ib_back:
                finish();
                break;
            case R.id.ac_6m_photo_btn_other_imags:
                break;
            case R.id.ac_6m_photo_btn_buhege2:
                break;
            case R.id.ac_6m_photo_btn_wancheng2:
                break;
        }
    }


    //发送拍照命令
    private void getDataTakePhoto(String plateType) {
        UtilsLog.e("getDataTakePhoto---url==" + SharedPreferencesUtils.getIP(instances) + PAIZHAO);

        String QueueID = "", GUID = "", Times = "",
                PlatformSN = "", SN = "", PhotoDate = "",
                PhotoType = "", Type = "", CarNO = "",
                PlateType = "",
                VIN = "", FileType = "jpg";
//        if (flag == 0) {
        QueueID = carsInforModel.getQueueID();
        GUID = carsInforModel.getGUID();
        Times = carsInforModel.getTimes();
        PlatformSN = carsInforModel.getPlatformSN();
        SN = carsInforModel.getSN();
        PhotoDate = DateUtil.currentTime2();
        PhotoType = PHOTO_TYPE;
        Type = carsInforModel.getType();
        CarNO = carsInforModel.getPlateNO();
        PlateType = carsInforModel.getPlateType();
        VIN = carsInforModel.getVIN();
//        } else if (flag == 1) {
//            QueueID = String.valueOf(recheckCarsModel.getQueueID());
//            GUID = recheckCarsModel.getGUID();
//            Times = String.valueOf(recheckCarsModel.getTimes());
//            PlatformSN = recheckCarsModel.getPlatformSN();
//            SN = recheckCarsModel.getSN();
//            PhotoDate = DateUtil.currentTime2();
//            PhotoType = PHOTO_TYPE;
//            Type = recheckCarsModel.getType();
//            CarNO = recheckCarsModel.getPlateRegion() +
//                    recheckCarsModel.getPlateNO();
//            PlateType = recheckCarsModel.getPlateType();
//            VIN = recheckCarsModel.getVIN();
//        }

        String str = "QueueID:" + QueueID + "\n" +
                "GUID:" + GUID + "\n" +
                "Times:" + Times + "\n" +
                "PlatformSN:" + PlatformSN + "\n" +
                "SN:" + SN + "\n" +
                "PhotoDate:" + PhotoDate + "\n" +
                "PhotoType:" + PhotoType + "\n" +
                "Type:" + Type + "\n" +
                "CarNO:" + CarNO + "\n" +
                "PlateType:" + PlateType + "\n" +
                "ItemCode:" + Item_Code + "\n" +
                "Line:" + acWai6mLine.getText().toString().trim() + "\n" +
                "VIN:" + VIN + "\n" +
                "FileType:" + FileType + "\n";
        UtilsLog.e("6米以上高度拍摄--照片getDataUploadPhoto---json==" + str);
        String logStr = "\n" + "6米以上高度拍摄--照片---json==" +
                "\n" + "json::" + str + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());


//        UploadPhotoModel model = new UploadPhotoModel();
//        model.setTimes(carsInforModel.getTimes());
//        model.setSN(carsInforModel.getSN());
//        model.setCarNO(carsInforModel.getPlateNO());
//        model.setFileType("jpg");
//        model.setGUID(carsInforModel.getGUID());
//        model.setItemCode("F2");
//        model.setLine(acWai6mLine.getText().toString().trim());
//        model.setPhotoDate(DateUtil.currentTime2());
//        model.setPlateType(carsInforModel.getPlateType());
//        model.setPlatformSN(carsInforModel.getPlatformSN());
//        model.setQueueID(carsInforModel.getQueueID());
//        model.setType(carsInforModel.getType());
//        model.setVIN(carsInforModel.getVIN());
//        model.setPhotoType(plateType);

        UploadPhotoModel model = new UploadPhotoModel();
        model.setTimes(Times);
        model.setSN(SN);
        model.setCarNO(CarNO);
        model.setFileType("jpg");
        model.setGUID(GUID);
        model.setItemCode("F2");
        model.setLine(acWai6mLine.getText().toString().trim());
        model.setPhotoDate(DateUtil.currentTime2());
        model.setPlateType(carsInforModel.getPlateType());
        model.setPlatformSN(PlatformSN);
        model.setQueueID(QueueID);
        model.setType(Type);
        model.setVIN(VIN);
        model.setPhotoType(plateType);

//        model.setZp(CommonUtils.imageToBase64(file));
        Gson gson = new Gson();
        String jsonStr = gson.toJson(model);
        String logStr11 = "\n" + "6米以上高度拍摄-发送拍照命令--参数" +
                "\n" + "json:" + jsonStr;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr11.getBytes());
        OkGo.<String>post(SharedPreferencesUtils.getIP(instances) + PAIZHAO).tag(instances)
                .upJson(jsonStr)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("getDataUploadPhoto-result==" + result);
                        String logStr = "\n" + "6米以上高度拍摄-start-请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getIP(instances) +
                                PAIZHAO + "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            if (result.contains("ok") || result.contains("OK")) {
//                                Toast.makeText(instances, "上传成功", Toast.LENGTH_LONG).show();
                            } else {
//                                Toast.makeText(instances, "上传失败，请重新拍照", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            UtilsLog.e("getDataUploadPhoto2-result==" + "没有数据");
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("getDataUploadPhoto2-onError==" + response.body());
                        UtilsLog.e("getDataUploadPhoto2-onError==" + response.getException());
                        String logStr = "\n" + "6米以上高度拍摄-start-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                PAIZHAO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);

                    }
                });
    }
}
